﻿using Hetang.Models.DataContext;
using Hetang.Models.Classes;
using Hetang.Models.Helper;
using Hetang.Models.Interface;
using Hetang.Models.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Hetang.Controllers
{
    public class JobController : Controller
    {
        IDatabaseRepository _dr;

        public JobController() : this(new DatabaseRepository()) { }

        public JobController(IDatabaseRepository dr)
        {
            _dr = dr;        
        }

        public ActionResult Index(string p)
        {
            using (HetangDataContext db = new HetangDataContext(DatabaseHelper.GetDatabaseConnect))
            {                
                int pageIndex = 1;
                if (!int.TryParse(p, out pageIndex))
                    pageIndex = 1;
                
                var companys = db.tbl_Company.OrderByDescending(c => c.ModifyDate).Select(c => new dt_Job { Id = c.Id, Name = c.Name, Recruit = c.Recruit }).Skip((pageIndex - 1) * 15).Take(15);

                if (!companys.Any())
                    companys = db.tbl_Company.OrderByDescending(c => c.ModifyDate).Select(c => new dt_Job { Id = c.Id, Name = c.Name, Recruit = c.Recruit }).Take(15);

                ViewBag.pageIndex = pageIndex;
                ViewBag.pageCount = db.tbl_Company.Count() / 15 + 1;
                return View(companys.ToList());
            }            
        }

        public ActionResult View(int? id)
        {
            if (id.HasValue)
            {
                if (id.Value.ToString().Length >= 7)
                {
                    tbl_Job job = _dr.GetJobByJobId(id);

                    if (job != null)
                    {
                        return View(job);
                    }
                    else
                    {
                        return RedirectToAction("manage");
                    }
                }
                else
                {
                    return RedirectToAction("manage");
                }
            }
            else
            {
                return RedirectToAction("manage");
            }
        }
    }
}
